//
// Created by huayang on 17-8-15.
//

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>

#include "tdss.h"
#include "tdss_utils.h"

int main() {

  size_t size = 1024 * 1024;
  const char* name = "packet.txt";

  Tdss* tdss = new Tdss;
  tdss->Init(name, size, "tdss", "1101");

  const char* id = std::string("2345678988").c_str();
  SegmentNode segment;
  segment.type = 1;
  segment.state = kUsed;
  memcpy(segment.id, id, strlen(id));

  int s = 17;
  for (int i = 0; i < s; ++i) {
    BaseData packet;
    std::string pkg = "com.qiku.cameramaster.qq";
    std::string val;
    std::stringstream ss;
    ss << i;
    val.append("Just this is cameramaster -- ").append(ss.str());
    std::string total = pkg + val;
    packet.segment = segment;
    packet.segment.name_length = pkg.size();
    packet.segment.total_length = total.size();
    packet.data = total.c_str();

    int err_code = tdss->AddData(packet);
    if (err_code == TdssErrCode::kErrFull) {
      std::cout << "--------------break add item---------------" << err_code << std::endl;
      break;
    }
  }
  std::cout << "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++" << std::endl;

  delete tdss;

  int fd = open(name, O_RDWR) ;
  std::cout << "fd : " << fd << std::endl;
  void* r_addr = mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
  struct Header* r_header = (Header *) r_addr;
  PrintHeader(r_header);

  for (int i = 0; i < kSections; ++i) {
    int s = r_header->section_offsets[i];
    if (s == 0) {
      continue;
    }
    Sections* ss = (Sections*)(r_addr + s);
    for (int j = 0; j < kEachSections; ++j) {
      SectionNode section = ss->sections[j];
      if (section.state != kUsed)
        continue;
      PrintSection(&section);
      auto * segs = (Segments*)((char*)r_addr + section.segments_offset);
      for (int k = 0; k < kEachSegments; ++k) {
        SegmentNode sgmt = segs->segments[k];
        if (sgmt.state != kUsed)
          continue;
        PrintSegment(&sgmt);
        std::string content = ReadContent(r_addr, sgmt);
        std::map<std::string, std::string> ret = ParseContent(content, sgmt);
        for (auto& m : ret) {
          std::cout << "k : " << m.first << std::endl;
          std::cout << "v : " << m.second << std::endl;
        }
      }
    }
  }

  return 0;
}